package com.wutma.job.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wutma.common.core.constants.CacheConstants;
import com.wutma.common.core.constants.Constants;
import com.wutma.common.redis.service.RedisService;
import com.wutma.job.domain.exam.entity.Exam;
import com.wutma.job.domain.message.Message;
import com.wutma.job.domain.message.MessageText;
import com.wutma.job.domain.message.vo.MessageTextVO;
import com.wutma.job.domain.user.UserScore;
import com.wutma.job.mapper.exam.ExamMapper;
import com.wutma.job.mapper.user.UserExamMapper;
import com.wutma.job.mapper.user.UserSubmitMapper;
import com.wutma.job.service.IMessageService;
import com.wutma.job.service.IMessageTextService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ExamXxlJob {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private IMessageTextService messageTextService;

    @Autowired
    private IMessageService messageService;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {
        // 修改未完赛的竞赛列表
        log.info("*** examListOrganizeHandler ***");
        List<Exam> unFinshList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(unFinshList, CacheConstants.EXAM_UNFINISHED_LIST);
        // 修改历史竞赛列表
        List<Exam> historyList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(historyList, CacheConstants.EXAM_HISTORY_LIST);
    }

    @XxlJob("examResultHandler")
    public void examResultHandler() {

        LocalDateTime nowDateTime = LocalDateTime.now();
        LocalDateTime minusDateTime= nowDateTime.minusDays(1);
        List<Exam> examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle)
                .eq(Exam::getStatus, Constants.TRUE)
                .ge(Exam::getEndTime, minusDateTime)
                .le(Exam::getEndTime, nowDateTime));
        Set<Long> examIdSet = examList.stream().map(Exam::getExamId).collect(Collectors.toSet());
        List<UserScore> userScores = userSubmitMapper.selectUserScore(examIdSet);
        Map<Long, List<UserScore>> userScoreMap = userScores.stream().collect(Collectors.groupingBy(UserScore::getExamId));
        createMessage(userScoreMap, examList);
    }

    private void createMessage(Map<Long, List<UserScore>> userScoreMap, List<Exam> examList) {
        List<MessageText> messageTextList = new ArrayList<>();
        List<Message> messageList = new ArrayList<>();
        for (Exam exam : examList) {
            Long examId = exam.getExamId();
            List<UserScore> userScoreList = userScoreMap.get(examId);
            int totalUser = userScoreList.size();
            int examRank = 1;
            for (UserScore userScore : userScoreList) {
               String msgTitle = exam.getTitle() + "--排名情况";
               String msgContent = "您所参与的竞赛" + exam.getTitle() + "本次参与人数共" + totalUser
                       + "人，您排名第" + examRank + "名";
                userScore.setExamRank(examRank);
                MessageText messageText = new MessageText();
                messageText.setMessageContent(msgContent);
                messageText.setMessageTitle(msgTitle);
                messageTextList.add(messageText);

                Message message = new Message();
                message.setSendId(Constants.SYSTEM_ID);
                message.setRecId(userScore.getUserId());
                messageList.add(message);
                examRank++;
            }
            userExamMapper.updateScoreAndRank(userScoreList); // 更新用户在竞赛中的积分排名情况
            redisService.rightPushAll(getExamRankListKey(examId), userScoreList);
        }
        messageTextService.batchMessageText(messageTextList);
        Map<String, MessageTextVO> messageTextVOMap = new HashMap<>();
        for (int i = 0;i < messageList.size();i++) {
            Message message = messageList.get(i);
            MessageText messageText = messageTextList.get(i);
            message.setTextId(messageText.getTextId());
            // 先报存好每个消息详情信息
            MessageTextVO messageTextVO = new MessageTextVO();
            BeanUtil.copyProperties(messageText, messageTextVO);
            String msgDetailKey = getMsgDetailKey(messageText.getTextId());
            messageTextVOMap.put(msgDetailKey, messageTextVO);
        }
        messageService.batchMessage(messageList);

        // 将数据存储到redis中
        // 1. 先将每个用户对应的专属信息存储到缓存中
        Map<Long, List<Message>> recUserMessageMap = messageList.stream().collect(Collectors.groupingBy(Message::getRecId));
        Iterator<Map.Entry<Long, List<Message>>> iterator = recUserMessageMap.entrySet().iterator();
        while (iterator.hasNext()) {
            // 拿到单个用户对应关系
            Map.Entry<Long, List<Message>> userMsgMap = iterator.next();
            Long userId = userMsgMap.getKey();
            List<Message> messages = userMsgMap.getValue();
            List<Long> msgTextIds = messages.stream().map(Message::getTextId).toList();
            String userMessageListKey = getUserMessageListKey(userId);
            redisService.rightPushAll(userMessageListKey, msgTextIds);
        }
        // 2. 将刚刚存储的 messageTextVOMap 批量存入缓存中
        redisService.multiSet(messageTextVOMap);
    }

    private String getMsgDetailKey(Long textId) {
        return CacheConstants.MESSAGE_DETAIL + textId;
    }

    public void refreshCache(List<Exam> examList, String examListKey) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(examListKey);
        redisService.rightPushAll(examListKey, examIdList); //刷新列表缓存
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getUserMessageListKey(Long userId) {
        return CacheConstants.USER_MESSAGE_LIST + userId;
    }

    private String getExamRankListKey(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }
}
